package net.chengp.ms.auth.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import net.chengp.ms.auth.constant.AuthConstant;
import net.chengp.ms.commons.result.R;
import net.chengp.ms.commons.result.Result;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		Result<?> result = R.error(HttpServletResponse.SC_UNAUTHORIZED, accessDeniedException.getMessage());
		response.setContentType(AuthConstant.APPLICATION_JSON_UTF8_VALUE);
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		response.getWriter().write(JSONObject.toJSONString(result));
	}
}